package com.dhms.lib.utils

import android.content.SharedPreferences
import android.os.Parcelable
import com.dhms.lib.app.LibApplication
import com.dhms.lib.app.LibApplication.Companion.mmkv
import com.google.gson.*
import com.tencent.mmkv.MMKV
import java.lang.reflect.Type
import java.util.*

class MkvSharedPreferences {

    companion object{
        /**
         * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
         */


        fun <T> store(key: String?, value: T?) {
            if (value is String) {
                mmkv?.encode(key, value as String?)
            } else if (value is Int) {
                (value as Int?)?.let { mmkv?.encode(key, it) }
            } else if (value is Boolean) {
                (value as Boolean?)?.let { mmkv?.encode(key, it) }
            } else if (value is Float) {
                (value as Float?)?.let { mmkv?.encode(key, it) }
            } else if (value is Long) {
                (value as Long?)?.let { mmkv?.encode(key, it) }
            } else if (value is Double) {
                (value as Double?)?.let { mmkv?.encode(key, it) }
            } else if (value is Set<*>) {
                mmkv?.encode(key, value as Set<String?>?)
            } else if (value is Parcelable) {
                mmkv?.encode(key, value as Parcelable?)
            } else {
                mmkv?.encode(key, value?.toString() ?: "")
            }
        }
        fun getValue(k: String?): String? {
            try {
                return mmkv?.decodeString(k, "")
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return ""
        }
        fun getValue(k: String?, defaultValue: Int): Int {
            return mmkv.decodeInt(k, defaultValue)
        }

        fun getValue(k: String?, defaultValue: Long): Long {
            return mmkv?.decodeLong(k, defaultValue) ?: 0L
        }

        fun getValue(k: String?, defaultValue: Boolean): Boolean {
            return mmkv?.decodeBool(k, defaultValue) ?: false
        }
        fun storeJson(k: String?, obj: Any?) {
            val builder = GsonBuilder()
            builder.registerTypeAdapter(Date::class.java, object : JsonDeserializer<Date?> {
                @Throws(JsonParseException::class)
                override fun deserialize(
                    json: JsonElement,
                    typeOfT: Type?,
                    context: JsonDeserializationContext?
                ): Date? {
                    return Date(json.asJsonPrimitive.asLong)
                }
            })
            val gson: Gson = builder.create()
            val v: String = gson.toJson(obj)
            //储存
            store(k, v)
        }

    }
}